<template>
  <el-drawer
    v-model="isDialog"
    :title="ruleForm.name"
    size="1200px"
    :before-close="cancel"
  >
    <div class="form-wrapper">
      <div class="custom-form">
        <public-number-list v-if="isList" @clickCard="clickCard"></public-number-list>
        <el-form
          v-if="!isList"
          :disabled="readOnly"
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          label-position="top"
        >
          <!-- <test></test> -->
          <el-form-item label="组件名称" prop="name">
            <el-input
              class="cop-name"
              v-model.trim="ruleForm.name"
              type="text"
              maxlength="15"
              :show-word-limit="true"
            >
            </el-input>
          </el-form-item>
        </el-form>
        <div v-if="!isList" class="temp-content">
          <el-form
            :disabled="readOnly"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            label-width="120px"
            label-position="top"
            class="demo-ruleForm"
          >
            <el-form-item label="选择公众号模板" prop="template_id">
              <el-select
                v-model="ruleForm.template_id"
                @change="setTemplateData(ruleForm.template_id)"
                placeholder="选择公众号模板"
              >
                <el-option
                  v-for="(item, idx) in templateList"
                  :key="idx"
                  :label="item.title"
                  :value="item.template_id"
                />
              </el-select>
            </el-form-item>
          </el-form>

          <div class="content">
            <div class="content-title">
              <span class="header-icon"></span>
            </div>
            <setVariablePub
              :isCareat="isCareat"
              :domData="domData"
              :comType="'publicNumber'"
              @subRuleForm="subRuleForm"
            ></setVariablePub>
          </div>
          <el-form
            :disabled="readOnly"
            label-width="120px"
            label-position="top"
            class="demo-ruleForm"
          >
            <el-form-item label="跳转">
              <div>
                <el-radio-group v-model="ruleForm.radioType" @change="clearRuleForm">
                  <el-radio
                    v-for="item in radioList"
                    :key="item.id"
                    :label="item.id"
                    border
                    >{{ item.name }}</el-radio
                  >
                </el-radio-group>
              </div>
            </el-form-item>
            <el-form-item v-if="ruleForm.radioType == 1">
              <el-input
                v-model="ruleForm.url"
                placeholder="请输入http://或https://开头的地址"
              />
            </el-form-item>
            <el-form-item v-if="ruleForm.radioType == 2">
              <el-input v-model="ruleForm.appid" placeholder="请输入小程序appID" />
            </el-form-item>
            <el-form-item v-if="ruleForm.radioType == 2">
              <el-input
                v-model="ruleForm.pagepath"
                placeholder="请输入小程序具体页面路径"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm()">确定</el-button>
      </div>
    </div>
    <WechatPreviewPubNum
      v-if="!isList"
      class="wechat-prevaiew"
      :content="content"
      :title="tepTitle"
    ></WechatPreviewPubNum>
  </el-drawer>
</template>

<script setup>
// import Dailog from '@/components/Dialog.vue'
import CanvasApi from "@/api/canvasApi.js";
import PublicNumberList from "./component/PublicNumberList.vue";
import setVariablePub from "@/components/marketingCanvas/component/setVariablePub.vue";
import WechatPreviewPubNum from "@/components/workWechat/WechatPreviewPubNum.vue";
// import { useGetCondition } from "@/components/marketingCanvas/compositions/useGetCondition";
import {NodeDrawerDataModel} from "@/views/workTable/dataModel/NodeDrawerDataModel";

const props = defineProps({
  addNodeEventData: Object,
  canvasData: Object,
  dialogData: {
    type: Object,
    default: {},
  },
  readOnly: Boolean,
});
const Store = useStore();
const emits = defineEmits(["confirm", "cancel"]);
const { dialogData, addNodeEventData, canvasData } = toRefs(props);

const { getActivity } = useGetCondition(canvasData.userGroupId);
const isDialog = ref(true);
const isList = ref(true);
const templateData = ref({});
const parentRuleForm = ref(null);
const domForm = ref({});
// ---------------------------------------------------------------------------------------------
const domData = ref({
  content: "",
});
const isCareat = ref(false);
const ruleFormRef = ref(null);

const ruleForm = reactive({
  name: "公众号模板消息",
  template_id: "",
  touser: "{{$_user.$_wxOpenId}}",
  url: null,
  appid: null,
  pagepath: null,
  data: {},
  radioType: 0,
  content: "",
  initialContent: "",
});

const rules = reactive({
  template_id: [
    {
      required: true,
      message: "请选择模板",
      trigger: ["change", "blur"],
    },
  ],
  name: [
    {
      required: true,
      message: "请输入组件名称",
      trigger: ["change", "blur"],
    },
  ],
});

const content = ref("");
const clearRuleForm = () => {
  ruleForm.url = null;
  ruleForm.appid = null;
  ruleForm.pagepath = null;
};
const templateList = ref([]);

const radioList = [
  { id: 0, name: "不跳转" },
  { id: 1, name: "链接" },
  { id: 2, name: "小程序" },
];
const submitForm = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid, fields) => {
    if (valid) {
      
    } else {
      
    }
  });
};

const resetForm = (ruleFormRef) => {
  if (!ruleFormRef) return;
  ruleFormRef.resetFields();
};
// 获取模板列表
const getPublicNumber = async () => {
  let rs = await CanvasApi.getPublicNumber();
  if (rs.code == 200) {
    
    templateList.value = rs.payload?.template_list ?? [];
  }
};
// 切换模板
const setTemplateData = (id) => {
  templateList.value.forEach((item) => {
    // debugger;
    
    if (item.template_id == id) {
      tepTitle.value = item.title;
      content.value = item.content;
      templateData.value = item;
      domData.value.content = item.content;
      ruleForm.initialContent = item.content;
      // domData.value = ruleForm.data
      isCareat.value = false;
      ruleForm.template_id = item.template_id;
      isList.value = false;
    }
  });
};
// -------------------------------------------------------------------------------------------------
const form = ref({
  words: "",
  attachments: [],
});
const tepTitle = ref("");
const clickCard = (item) => {
  // debugger;
  tepTitle.value = item.title;
  content.value = item.content;
  templateData.value = item;
  domData.value = templateData.value;
  ruleForm.initialContent = templateData.value.content;
  isCareat.value = true;
  ruleForm.template_id = item.template_id;
  isList.value = false;
};
const subRuleForm = (form) => {
  // debugger
  ruleForm.data = form;
  

  
  ruleForm.data = form;

  let initialContent = ruleForm.initialContent;
  for (let item in form) {
    // debugger;
    
    if (form[item].value) {
      // debugger;
      let key = new RegExp(`{{${item}.DATA}}`, "g");

      initialContent = initialContent.replace(key, form[item].value);
    }
    
  }
  
  ruleForm.content = initialContent;
  content.value = initialContent;
  
};

const handleConfirm = () => {
  emits(
    "confirm",
    new NodeDrawerDataModel({
      dialogData: {
        name: ruleForm.name,
        reachBody: JSON.stringify(ruleForm),
        reachType: 4,
        url: ruleForm.url,
        appid: ruleForm.appid,
        pagepath: ruleForm.pagepath,
      }
    })
  );

  cancel();
};
const cancel = () => {
  emits("cancel");
};

onBeforeMount(async () => {
  getPublicNumber()
  // if (JSON.stringify(Store.state.event.eventObj.activity) == "{}") {
  //   await getActivity();
  // }

  // debugger;
  if (JSON.stringify(dialogData.value) != "{}") {
    let params = JSON.parse(dialogData.value.reachBody);
    
    ruleForm.url = params.url;
    ruleForm.appid = params.appid;
    ruleForm.pagepath = params.pagepath;
    ruleForm.radioType = params.radioType;
    ruleForm.content = params.content;
    ruleForm.initialContent = params.initialContent;
    domData.value.content = params.initialContent;
    domData.value.data = params.data;
    ruleForm.data = params.data;
    ruleForm.name = dialogData.value.name;

    ruleForm.template_id = templateData.value.template_id || params.template_id;

    // 
    // form.phones = params.phones;
    // form.content = params.content;
    // form.attachments = params.attachments;
    templateList.value.forEach((item) => {
      if (item.template_id == params.template_id) {
        domData.value = params;
        domData.value["content"] = item.content;
        content.value = item.content;
        tepTitle.value = item.title;
      }
    });
    subRuleForm(ruleForm.data);

    isList.value = false;
  }
});
</script>
<style lang="scss" scoped>
.top-tip {
  overflow: hidden;
  width: 454px;
  line-height: 36px;
  color: #3e61a9;
  font-weight: 400;
  background: #e8f2ff;
  font-size: 13px;
  padding-left: 17px;
  border-radius: 4px;
  font-family: PingFangSC-Regular, PingFang SC;
  position: relative;
  .el-icon {
    // margin-top: 25px;
    position: relative;
    top: 2px;
  }
}

.center-tip {
  position: relative;
  width: 454px;
  height: 56px;
  background: #f6faff;
  border-radius: 4px;
  line-height: 20px;
  font-size: 13px;
  font-weight: 400;
  color: #909399;
  padding: 8px 7px 8px 24px;
  font-family: PingFangSC-Regular, PingFang SC;
  .circular {
    display: block;
    width: 6px;
    height: 6px;
    background: #3e61a9;
    border-radius: 50%;
    position: absolute;
    left: 10px;
    top: 15px;
  }
}
.form-wrapper {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.custom-form {
  flex: 1;
}
.form-footer {
  display: flex;
  justify-content: flex-end;
  position: fixed;
  right: 50px;
  bottom: 20px;
}
.wechat-prevaiew {
  position: fixed;
  top: 10%;
  right: 30px;
}
.temp-content {
  width: 482px;
  padding: 20px 30px;
  background: #fafcff;
  border-radius: 5px;
  :deep(.item-add) {
    width: 440px;
  }
  :deep(.item-content) {
    width: calc(100% - 80px);
  }
}
.cop-name {
  width: 540px;
}
.el-select {
  width: 440px;
}
</style>
